<template>
    <div class="blog-toc-container">
        <h2>目录</h2>
        <RightList :list="tocWithSelectCom" @select="handleSelect"></RightList>
    </div>
</template>
<script setup lang='ts'>
import { PropType, computed, onMounted, onUnmounted, ref } from 'vue';
import RightList from '../rightList/RightList.vue';    
import { RightListItemInter } from '../rightList/types';
import { $bus } from '~@/bus/busIndex';
import { debounce } from '~@/untils/NslUtils';
    //#region defineXxx
    defineOptions({
        name:'BlogToc'
    });

    const props=defineProps({
        toc:{
            type:Array as PropType<RightListItemInter[]>,
            required:true
        },
    });

    const emit = defineEmits<{
        event1:[para1:number,para2:string],
        event2:[para1:number,para2:string],
    }>();
    //#endregion

    const activeAnchorRef=ref('');

    const tocWithSelectCom=computed<RightListItemInter[]>(()=>{
        const getToc:any=(toc:RightListItemInter[]=[])=>{
            return toc.map((e)=>({
                ...e,
                isSelected:e.anchor===activeAnchorRef.value,
                children:getToc(e.children)
            }));
        }
        return getToc(props.toc);
    })
  
    const domsCom=computed(()=>{
        const doms:HTMLElement[]=[];
        const addToDoms=(toc:RightListItemInter[])=>{
            toc.forEach(e=>{
                if(e.anchor){
                    if(document.getElementById(e.anchor)){
                        doms.push(document.getElementById(e.anchor) as HTMLElement);
                        if(e.children){
                            addToDoms(e.children);
                        }
                    }
                }
            })
        }
        addToDoms(props.toc);
        return doms;
    })

    const setSelectDebounced=debounce(()=>{
        activeAnchorRef.value='';// 由于后续要重新设置，先清空之前的状态
        const range=200;//200px 
        domsCom.value.forEach(e=>{
            const top=e.getBoundingClientRect().top;
            if(e){
                if(top<range){
                    activeAnchorRef.value=e.id;//注意理解，遍历doms，最后一个在范围内的，即激活的
                }
            }
        })
    },50)

    const handleSelect=((item:any)=>{
        console.log(item);
        location.hash=item.anchor;
    })


    onMounted(()=>{
        $bus.on('mainScroll',setSelectDebounced);
    });

    onUnmounted(()=>{
        $bus.off('mainScroll',setSelectDebounced);
    })
    
</script>
<style lang='less' scoped>
.to-top-container {
  background: @primary;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  position: fixed;
  z-index: 99;
  right: 50px;
  bottom: 50px;
  cursor: pointer;
  line-height: 50px;
  color: #fff;
  text-align: center;
}    
</style>